import React, { useState, useEffect, useRef } from 'react';
import { Button, Col, ConfigProvider, DatePicker, Form, Input, Radio, Row, Table } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import { applicationStatus } from '@/utils/trainUtil';
import { SearchOutlined } from '@ant-design/icons';
import moment from 'moment';
import {
  getApplicationList,
  getApplicationInfoById,
} from '@/services/PersonalCenter/applicationQuery';
import { getUserInfo } from '@/utils/storage';
import ApplicationDetailModal from './Componets/ApplicationDetailModal';
import classnames from 'classnames';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';

const layout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 17 },
};

const ApplicationQuery: React.FC = () => {
  const tableRef = useRef<ActionType>();
  const userInfo = getUserInfo();
  const [month, setMonth] = useState('');
  const [status, setStatus] = useState('');
  const [applicationData, setApplicationData] = useState([]);
  const [keyWords, setKeyWords] = useState('');
  const [searchCondition, setSearchCondition] = useState({
    companyId: userInfo.userId,
  });
  const [pageParams, setPageParams] = useState({
    page: 1,
    size: 20,
  });
  const [modalParams, setModalParams] = useState<{ visible: boolean; type?: string }>({
    visible: false,
    type: '',
  });

  const [detailData, setDetailData] = useState([]);

  const handleStatusChange = (e: any) => {
    setStatus(e.target.value);
    setSearchCondition({
      companyId: userInfo.userId,
      applyTime: month,
      keyword: keyWords,
      applyStatus: e.target.value,
    });
  };
  function onMonthChange(date: any, dateString: any) {
    if (dateString === '') {
      setMonth('');
      setSearchCondition({
        ...pageParams,
        companyId: userInfo.userId,
        applyTime: '',
        applyStatus: status,
        keyword: keyWords,
      });
    } else {
      setMonth(dateString);
      setSearchCondition({
        ...pageParams,
        companyId: userInfo.userId,
        applyTime: dateString,
        applyStatus: status,
        keyword: keyWords,
      });
    }
  }
  const onFinish = (values: any) => {
    // console.log('values =========', values);
    const { applyTime, keyWords } = values;
    setKeyWords(keyWords);
    if (applyTime !== null && applyTime !== undefined) {
      setSearchCondition({
        ...pageParams,
        companyId: userInfo.userId,
        applyTime: moment(applyTime).format('YYYY-MM'),
        keyword: keyWords,
        applyStatus: status,
      });
    } else {
      setSearchCondition({
        ...pageParams,
        companyId: userInfo.userId,
        applyTime: '',
        keyword: keyWords,
        applyStatus: status,
      });
    }
  };
  const getModal = async (type: string, id: any) => {
    setModalParams({ visible: true, type });
    await getApplicationInfoById({ id })
      .then((resp) => {
        setDetailData(resp?.results);
      })
      .catch((error) => {
        throw error;
      });
  };
  const columns: ProColumns[] = [
    {
      title: '申请项目编号',
      dataIndex: 'applyNo',
      key: 'applyNo',
      width: 60,
    },
    {
      title: '事项名称',
      dataIndex: 'matterTitle',
      key: 'matterTitle',
      width: 100,
    },
    {
      title: '申请时间',
      dataIndex: 'applyTime',
      key: 'applyTime',
      width: 150,
    },
    {
      title: '申请金额(元)',
      dataIndex: 'applyAmount',
      key: 'applyAmount',
      width: 80,
    },
    {
      title: '申请状态',
      key: 'applyStatus',
      dataIndex: 'applyStatus',
      width: 70,
      render: (text: string) => {
        if (text === '00') return '全部';
        if (text === '01') return '办理中';
        if (text === '02') return '已完成';
        if (text === '03') return '中止申请';
        return '补充材料';
      },
    },
    {
      title: '操作',
      key: 'actions',
      valueType: 'actions',
      width: 40,
      render: (text, record) => {
        return (
          <div
            className={classnames(`${styles.tableOpt}`)}
            onClick={
              record?.applyStatus === '04'
                ? getModal.bind('', 'detailAdd', record?.id)
                : getModal.bind('', 'detail', record?.id)
            }
          >
            查看
          </div>
        );
      },
    },
  ];
  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.ApplicationQueryWrapper}>
        <div className={styles.ApplicationQueryTitle}>
          <div className={styles.titleLeft}>
            <div className={styles.sideShortBar}></div>
            <div className={styles.titleText}>申请查询</div>
          </div>
          <div className={styles.titleRight}>
            <Form {...layout} className={styles.ApplicationQueryForm} onFinish={onFinish}>
              <Row>
                <Col>
                  <Form.Item label="申请时间" name="applyTime">
                    <DatePicker onChange={onMonthChange} picker="month" placeholder="请选择" />
                  </Form.Item>
                </Col>
                <Col span={1}></Col>
                <Col>
                  <Form.Item label="关键字" name="keyWords">
                    <Input className={styles.SearchInput} placeholder="申请编号或事项名称" />
                  </Form.Item>
                </Col>
                <Col>
                  <Form.Item>
                    <Button
                      className={styles.SearchInput}
                      type="primary"
                      htmlType="submit"
                      icon={<SearchOutlined />}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={styles.filterContent}>
          <div className={styles.filterItem}>
            <div className={styles.conditionTitle}>申请状态：</div>
            <div className={styles.conditionList}>
              <Radio.Group value={status} onChange={handleStatusChange}>
                {applicationStatus?.map((item) => {
                  return (
                    <Radio.Button key={item.key} value={item.value}>
                      {item.title}
                    </Radio.Button>
                  );
                })}
              </Radio.Group>
            </div>
          </div>
        </div>
        <div className={styles.showTotalNum}>
          共{applicationData?.length === undefined ? 0 : applicationData?.length}条数据
        </div>
        <div className={styles.ApplicationQueryTable}>
          <ConfigProvider locale={zhCN}>
            <ProTable
              columns={columns}
              size="middle"
              actionRef={tableRef}
              search={false}
              params={searchCondition}
              toolBarRender={false}
              request={async (params, sorter, filter) => {
                const resp = await getApplicationList(searchCondition);
                if (resp?.results) {
                  setApplicationData(resp.results);
                  return {
                    data: resp.results,
                    success: true, // 设为true, 才能显示数据
                    total: resp.totalCount, // 分页使用
                  };
                }
              }}
              pagination={{
                locale: zhCN,
                total: applicationData?.length,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => {
                  return `共${total}条数据`;
                },
                onChange: (page, pageSize) => {
                  setPageParams({
                    page,
                    size: pageSize,
                  });
                },
              }}
            />
          </ConfigProvider>
        </div>
        <ApplicationDetailModal
          {...modalParams}
          closeModal={() => setModalParams({ visible: false })}
          data={detailData}
          onSuccess={() => {
            tableRef.current?.reload();
          }}
        />
      </div>
    </ConfigProvider>
  );
};

export default ApplicationQuery;
